package com.cards_game.simple_ddz.component;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;

import com.cards_game.simple_ddz.bean.PlayerBean;
import com.cards_game.simple_ddz.common.AllPrimaryContainer;
import com.cards_game.simple_ddz.common.RoomBean;
import com.cards_game.simple_ddz.constants.CommonConstants;

/**
 * @author 郭国辉
 * 
 *     2017年6月25日上午1:53:36
 */
public class InAndOutRoom {
	
	private static ConcurrentHashMap<Integer, RoomBean> playerRoomMap = AllPrimaryContainer.getAllPrimaryContainer().getPlayerRoomMap();
	private static ConcurrentSkipListSet<RoomBean> notFullRooms = AllPrimaryContainer.getAllPrimaryContainer().getNotFullRooms();
	private static final int FAIL_NUM=10;
	
	public static RoomBean intoRoom(int userId){
		RoomBean room =null;
		if((room=playerRoomMap.get(userId))!=null){
			return room;
		}
		boolean allotSucceed = false;
		int times=0;
		
		PlayerBean player=new PlayerBean();
		player.setId(userId);
		player.setReady(true);
		/*
		 * 如果未满房间不为空，但是分配失败 则重新分配
		 * 失败10次，则放弃
		 */
		while (notFullRooms != null && !allotSucceed) {
			room = notFullRooms.last();
			allotSucceed = accessRoom(player, room);
			times++;
			//如果10次仍未匹配到适合的房间，放弃
			if(times==FAIL_NUM){
				break;
			}
		}
		return room;
	}
	/**
	 * 进入房间
	 * 
	 * @param player
	 * @param room
	 * @return 成功返回 true 失败返回false
	 */
	public static boolean accessRoom(PlayerBean player, RoomBean room) {
		if (room.getPlayerList().size() < CommonConstants.PLAYER_TOTAL) {
			synchronized (room) {
				if (room.getPlayerList().size() < CommonConstants.PLAYER_TOTAL) {
					//先从未满房间队列中移除该房间，如果之后判断该房间依旧未满，则加入，否则，不再加入
					notFullRooms.remove(room);
					room.getPlayerList().add(player);
					
					//如果房间仍然未满，将该房间加入未满房间容器
					if(room.getPlayerList().size() < 3){
						notFullRooms.add(room);
					}
					playerRoomMap.put(player.getId(), room);
					return true;
				}
			}
		}
		return false;
	}
}
